package leetcode;

import javax.swing.tree.TreeNode;

public class Solution9 {
    public boolean isBalanced(TreeNode root) {
        return getHieght(root) != -1;
    }

    public int getHieght(TreeNode node){
        if(node == null){
            return 0;
        }
        //左子树
        int leftHeight = getHieght(node.left);
        if(leftHeight == -1 ){
            return -1;
        }
        //右子树
        int rightHeightt = getHieght(node.right);
        if(rightHeightt == -1){
            return -1;
        }
        //中间节点
        if(Math.abs(leftHeight - rightHeightt) > 1){
            return -1;
        }

        int result = 0;
        result = 1 + Math.max(leftHeight,rightHeightt);
        return result;
    }
}
